package org.hhqk.admin.controller;



import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.hhqk.mybatis.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * @author Administrator
 * MainController.java
 * 2017年10月31日
 * <p>description:</p>
 */
@Controller
public class MainController{
	
	//进入登录页面
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String goLogin(){
		//用户已经登录状态下，直接跳转,获取shiro session 里 的用户，如果存在就直接进入主页面
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		User user = (User) session.getAttribute("CurrentUser");
		if(user!=null){
			return "redirect:/home";
		}
		return "login";
	}
	
	//登录验证请求   shiro successUrl 配置失效，重定向到项目根目录了
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String Login(String username,String password,Boolean rememberMe){
		//验证登录的用户名和密码
		try {
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
			subject.login(token);
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
        return "home";
	}
	
	@RequestMapping(value = "/home", method = RequestMethod.GET)
    public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView mav = new ModelAndView();
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User user = (User) session.getAttribute("CurrentUser");
        if (user != null) {
            mav.setViewName("main/index");
        }
        return mav;
    }
	
}
